<template>
    <el-dialog
        class="custom-modal"
        title="设置选项"
        :visible.sync="show"
        append-to-body
        top="20vh"
        @open="_open"
        @close="_close"
        @closed="_afterClose"
        :close-on-click-modal="false"
        v-auto-focus>
        <div>
            <p>每行对应一个选项，修改后显示条件将被清空</p>
            <el-input type="textarea" v-model="optionsListValue" :rows="5"></el-input>
        </div>
        <div slot="footer" class="dialog-footer">
            <el-button @click="close">取消</el-button>
            <el-button class="sure" type="primary" @click="sure" :loading="ajaxLoader">保存</el-button>
        </div>
    </el-dialog>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import { getRandomId } from "@/utils";
import draggable from "vuedraggable";

@Component({
    components: {
        draggable
    }
})
export default class UpDateOptions extends Vue {
    show = false;
    ajaxLoader = false;
    optionsList: any = [];
    optionsListValue = "";
    oldValue = ";"

    async _open() {
        this.optionsListValue = this.optionsList.map((item: any) => item.name).join(`\n`) + `\n`;
        this.oldValue = this.optionsListValue;
        this.$emit("onopen");
    }

    _close() {
        this.$emit("onclose");
    }

    _afterClose() {
        this.$nextTick(function() {
            this.$emit("onafterclose");
            this.$el.remove && this.$el.remove();
        });
    }

    close() {
        this.show = false;
        this.optionsListValue = "";
        this.oldValue = "";
        this.$emit("close");
    }

    async sure() {
        if (this.oldValue === this.optionsListValue) {
            this.$emit("sure", this.optionsList);
            return;
        }
        const list: any = [];
        const nameList = Array.from(new Set(this.optionsListValue.split(`\n`)));
        nameList.forEach((item: any) => {
            if (!item.match(/^[ ]*$/)) {
                list.push({
                    name: item,
                    tempId: getRandomId()
                });
            }
        });
        this.$emit("sure", list);
    }
}
</script>

<style lang="scss" scoped>
::v-deep {
    .el-dialog__body {
        padding-top: 0;
    }
}
</style>
